/**
 * 
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 * 
 *   http://www.apache.org/licenses/LICENSE-2.0
 *   
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 * 
 */
package org.jiopi.ibean.setup;

import java.io.File;
import java.net.URL;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.jiopi.framework.core.Config;
import org.jiopi.ibean.loader.IBeanLoaderConstants;
import org.jiopi.ibean.loader.log.LoaderLogUtil;
import org.jiopi.ibean.share.ShareConstants;
import org.jiopi.ibean.share.ShareUtil.ClassUtil;
import org.jiopi.ibean.share.ShareUtil.FileUtil;
import org.jiopi.ibean.share.ShareUtil.ResourceUtil;

/**
 * 
 * @since 2010.4.9
 *
 */
public class SetupImpl implements Setup {

	public void setup() {
		Logger setupLogger = LoaderLogUtil.getLoaderLogger(SetupConstants.SETUP_NAME);
		setupLogger.info(SetupConstants.COPY_RIGHT);
		ClassLoader myClassLoader = ClassUtil.getClassLoaderByClass(SetupImpl.class);
		Properties setupProperties = ResourceUtil.getPropertiesFromClassPath(myClassLoader, IBeanLoaderConstants.SETUP_CONFIG_FILE,false);
		String iBeanVersion = setupProperties.getProperty(SetupConstants.IBEAN_VERSION);
		setupLogger.info("found iBean version "+iBeanVersion);
		
		
		String programDir = setupProperties.getProperty(SetupConstants.PROGRAM_DIR);
		//获取iBeanHome目录
		String iBeanHomePath = Config.getConfig(ShareConstants.IBEAN_HOME);
		programDir = FileUtil.joinPath(iBeanHomePath,programDir);//生成下载资源根目录路径
		
		
		String iBeanProgramPath = ResourceUtil.getIBeanProgramDir();
		
		//生成版本完成字符串和目录名
		String versionString = ResourceUtil.getVersionString(iBeanVersion, -1);
		if(setupLogger.isLoggable(Level.FINEST)) setupLogger.finest("versionString:"+versionString);
		String version = ResourceUtil.getVersionDirName(versionString);
		if(setupLogger.isLoggable(Level.FINEST)) setupLogger.finest("versionDir:"+version);
		
		String iBeanVersionProgramPath = FileUtil.joinPath(iBeanProgramPath,version);
		
		ArrayList<URL> downloadURLList = new ArrayList<URL>();//服务器端资源
		ArrayList<File> downloadFileList = new ArrayList<File>();//对应的本地文件资源
		Enumeration<Object> keys = setupProperties.keys();
		while( keys.hasMoreElements() ) {
			String key = (String) keys.nextElement();
			if( key.startsWith( SetupConstants.RESOURCE_PREFIX ) ) {
				String resource = setupProperties.getProperty(key);
				String downloadURL = FileUtil.joinPath(programDir,resource);
				String downloadFile = FileUtil.joinPath(iBeanVersionProgramPath,resource);
				if(setupLogger.isLoggable(Level.FINEST)) setupLogger.finest("downloadURL:"+downloadURL);
				if(setupLogger.isLoggable(Level.FINEST)) setupLogger.finest("downloadFile:"+downloadFile);
				downloadURLList.add(FileUtil.toURL(downloadURL));
				downloadFileList.add(new File(downloadFile));
			}
		}
		boolean setupOK = true;
		boolean runOver = false;
		//开始下载
		try{
			int totalResourceNum = downloadURLList.size();
			if(totalResourceNum!=downloadFileList.size()) setupOK = false;
			if(setupOK){
				for(int i=0;i<totalResourceNum;i++){
					URL fromURL = downloadURLList.get(i);
					File toFile = downloadFileList.get(i);
					ResourceUtil.copyContent(fromURL, toFile, false);
					if(!toFile.isFile()){//下载失败
						setupOK = false;
						setupLogger.severe("Download from "+fromURL.toString()+" to "+toFile.getCanonicalPath()+" ERROR!");
						break;
					}
					setupLogger.info("Download from "+fromURL.toString()+" to "+toFile.getCanonicalPath()+" success!");
				}
			}
			if(setupOK){
				//生成目录
				String versionFinishFilePath = FileUtil.joinPath(iBeanProgramPath,".ver"+versionString);
				FileUtil.createNewFile(versionFinishFilePath, false);
			}
			runOver = true;//执行完毕所有操作
		}catch(Exception e){
			setupOK = false;
			LoaderLogUtil.logExceptionTrace(setupLogger, Level.SEVERE, e, "Download iBean program ERROR!");
		}
		finally{
			if(!runOver||!setupOK){
				//清除没有下载完成标记的目录
				ResourceUtil.deleteUnfinishedVersionDir(new File(iBeanProgramPath));
			}
		}
	}
}
